import { Component, OnInit, ViewChild } from '@angular/core';
import { PageEntity } from '../../../core/domain/page.entity';
import { ClassMajorTreeComponent } from '../class-major-tree/class-major-tree.component';
import { ClassManageService } from './class-manage.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ClassInfos } from './domain/class';
import { CopyUtil } from '../../../utils/copy.util';
import { SelfValidators } from '../../../utils/self.validators';
import { StatusEnum } from '../../../core/enum/status.enum';
import { FilterEnum, FilterTypeEnum } from '../../../core/enum/filter.enum';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { OtherUtil } from '../../../utils/other.util';
import { HTTP_BASE_URL, SERVERS_NAME } from '../../../config/config';
import { StorageUtil } from '../../../utils/storage.util';
import {PostDown} from '../../../utils/postdown';

@Component({
  selector: 'app-class-manage',
  templateUrl: './class-manage.component.html',
  styleUrls: ['./class-manage.component.scss'],
  providers: [ClassManageService, PostDown]
})
/**
 * @author zhouxin
 * @date 2019-04-20
 * @description 班级管理
 */
export class ClassManageComponent implements OnInit {
  // 树
  @ViewChild('treeDom')
  treeDom: ClassMajorTreeComponent;
  pageInfo: PageEntity = new PageEntity();
  pageInfoCampus: PageEntity = new PageEntity();
  isVisible = false;
  validateForm: FormGroup;
  className = '';
  classList = [];
  isAllCheck = false;
  isIndeterminate = false;
  displayList = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  classInfos: ClassInfos = new ClassInfos();
  collageList = [];
  majorList = [];
  yearList = [];
  headTeacherList = [];
  roleManager = 1;

  // 当前点击的事件何种类型的数据
  currentType = '';

  canDelete = true;

  // 导入
  showExcelModal = false;
  importExcelName = '';
  fileListImport: UploadFile[] = [];
  campusList = []; // 校区下拉框

  constructor(private classManageService: ClassManageService,
              private fb: FormBuilder,
              private message: NzMessageService,
              private postDown: PostDown) {
  }

  ngOnInit() {
    this.initForm();
    this.getCollegeList();
    this.getTeachList();
    this.yearList = this.getYear();
    // this.roleManager = StorageUtil.getLocalStorage('roleManager');
    this.pageInfoCampus.filters['type'.toString()] = {
      matchMode: 'contains',
      value: 'school-type',
      whereType: 'AND'
    };
    this.pageInfoCampus.multiSortMeta = [
      {
        field: 'type',
        order: 1
      },
      {
        field: 'orderLevel',
        order: 1
      }
    ];
    this.getCampusList(this.pageInfoCampus);
  }

  queryIds(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  /**
   * 获取校区下拉框
   */
  getCampusList(page: PageEntity) {
    this.classManageService.getCampusDic(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.campusList = res.datas.data;
      }
    });
  }

  /**
   * 校验
   */
  initForm() {
    this.validateForm = this.fb.group({
      collageId: [this.classInfos.collageId, [Validators.required]],
      majorId: [this.classInfos.majorId, [Validators.required]],
      schoolYear: [this.classInfos.schoolYear, [Validators.required]],
      name: [this.classInfos.name, [Validators.required]],
      headTeacherId: [this.classInfos.headTeacherId, [Validators.required]],
      monitor: [this.classInfos.monitor, []],
      telphone: [this.classInfos.telphone, []],
      remark: [this.classInfos.remark, []],
      xqmc: [this.classInfos.xqmc, [Validators.required]]
    });
  }

  /**
   * 树点击
   * @param event 树参数
   */
  clickTree(event) {
    this.className = null;
    this.pageInfo = new PageEntity();
    delete this.pageInfo.filters['name'.toString()];
    if (event.pId) {
      this.classInfos.collageId = event.pId;
      this.classInfos.majorId = event.id; // id
    }
    if (!event.pId) {
      this.classInfos.collageId = event.id;
      this.classInfos.majorId = event.id; // id
    }
    this.currentType = event.type;
    this.dealPage();
    this.getPage(this.pageInfo);
  }

  /**
   * 分页查询
   * @param page 分页条件
   */
  getPage(page: PageEntity): void {
    this.classManageService.getClassList(page).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.classList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }

  dealPageLogic(pageConfig: PageEntity, filterVal: any, curVal: any, mode: any): void {
    pageConfig.filters[filterVal.toString()] = {
      matchMode: mode,
      value: curVal,
      whereType: FilterTypeEnum.AND
    };
  }

  dealPage(): void {
    if (this.currentType) {
      if (this.currentType === '0') {
        // 部门
        this.dealPageLogic(this.pageInfo, 'collageId', this.classInfos.majorId, FilterEnum.EQUALS);
        delete this.pageInfo.filters['majorId'.toString()];
      } else {
        // 专业
        this.dealPageLogic(this.pageInfo, 'majorId', this.classInfos.majorId, FilterEnum.EQUALS);
        delete this.pageInfo.filters['collageId'.toString()];
      }
    }
    // tslint:disable-next-line:max-line-length
    this.className ? this.dealPageLogic(this.pageInfo, 'name', this.className, FilterEnum.CONTAINS) : delete this.pageInfo.filters['name'.toString()];
  }

  /**
   * 进行搜索
   */
  search(): void {
    this.pageInfo = new PageEntity();
    this.dealPage();
    this.getPage(this.pageInfo);
  }

  /**
   * 点击重置
   */
  resetSearch() {
    this.className = '';
    delete this.pageInfo.filters['name'.toString()];
    this.getPage(this.pageInfo);
  }

  /**
   * 当前页面展示数据改变的回调函数
   */
  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  /**
   * 单选
   */
  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.queryIds();
  }

  /**
   * 全选
   */
  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
    this.queryIds();
  }

  /**
   * 获取部门
   */
  getCollegeList() {
    this.classManageService.getCollegeList({}).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.collageList = res.datas;
      }
    });
  }

  /**
   * 获取专业
   */
  getMajorList() {
    if (this.classInfos.collageId) {
      this.classManageService.getMajorList([this.classInfos.collageId]).subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          this.majorList = res.datas;
          if (this.classInfos.majorId) {
            if (this.classInfos.collageId === this.classInfos.majorId) {
              // tslint:disable-next-line:max-line-length
              this.majorList.length < 1 ? this.message.warning('该部门下暂无专业，请先添加!') : this.classInfos.majorId = this.majorList[0].value;
            }
          } else {
            this.majorList.length < 1 ? this.message.warning('该部门下暂无专业，请先添加!') : this.classInfos.majorId = this.majorList[0].value;
          }
        }
      });
    }
  }

  /**
   * 获取教师
   */
  getTeachList() {
    this.classManageService.getTeachList().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.headTeacherList = res.datas;
      }
    });
  }

  /**
   * 班级新增
   */
  clickAdd() {
    this.classInfos.id = null;
    this.classInfos.monitor = null;
    this.classInfos.name = null;
    this.classInfos.remark = null;
    this.classInfos.schoolYear = null;
    this.classInfos.telphone = null;
    this.classInfos.headTeacherId = null;
    this.classInfos.xqmc = null;
    this.classInfos.collageId = null;
    this.classInfos.majorId = null;
    this.collageList = [];
    this.majorList = [];
    this.initForm();
    this.getCollegeList();
    this.getTeachList();
    this.isVisible = true;
  }

  /**
   * 部门change
   */
  collegeChange(event: any) {
    if (event === '0') { return false; }
    this.classInfos.majorId = null;
    this.getMajorList();
  }

  /**
   * 提交
   */
  submit() {
    this.classInfos.id ? this.editSubFn() : this.addSubFn();
  }

  /**
   * 校区下拉框改变时
   */
  changeCampus(keyCode) {
    this.campusList.map(item => {
      if (item.keyCode === keyCode) {
        this.classInfos.xqhId = item.keyValue;
      }
    });
  }

  /**
   * 新增提交
   */
  addSubFn(): void {
    this.classManageService.submit(this.classInfos).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.isVisible = false;
        this.getPage(this.pageInfo);
      }
    });
  }

  /**
   * 编辑提交
   */
  editSubFn(): void {
    this.classManageService.update(this.classInfos).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.isVisible = false;
        this.getPage(this.pageInfo);
      }
    });
  }

  /**
   * 编辑
   * @param data 数据
   */
  editClass(data) {
    this.classInfos = CopyUtil.deepCopy(data, {});
    this.getCollegeList();
    this.isVisible = true;
  }

  /**
   * 删除
   * @param ids id
   */
  deleteClass(ids) {
    const data = {
      id: ids
    };
    this.classManageService.delete(data).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.getPage(this.pageInfo);
      }
    });
  }

  /**
   * 删除所有
   */
  deleteAll() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    if (arr.length < 1) {
      this.message.warning('请勾选要删除的数据!');
      return;
    }
    this.classManageService.deleteAll(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success(res.message);
        this.mapOfCheckedId = {};
        // this.pageInfo.first = 1;
        this.getPage(this.pageInfo);
      }
    });
  }

  cancelFn(): void {
    this.canDelete = true;
    this.isAllCheck = false;
    this.mapOfCheckedId = {};
    this.isIndeterminate = false;
  }

  /**
   *  获取前五年份
   */
  getYear() {
    const endyear = new Date().getFullYear();
    const startyear = endyear - 4;
    const yearList = [];
    for (let j = startyear; j <= endyear; j++) {
      yearList.push(j);
    }
    return yearList;
  }

  /**
   * 显示导入
   */
  importShow(): void {
    this.showExcelModal = true;
  }

  /**
   * 1：导出选中；2：导出当前页；3：导出全部
   */
  exportShow(num: number): void {
    const obj = {
      mode: num,
      pager: {},
      sourceIds: []
    };
    if (num === 1) {
      obj.pager = {};
      obj.sourceIds = Object.keys(this.mapOfCheckedId).filter(k => this.mapOfCheckedId[k] === true);
    } else if (num === 3) {
      obj.pager = this.pageInfo;
      obj.sourceIds = [];
    }
    this.postDown.postDownload('security-server/dietc/sys/classes/exportExcel2', obj);
  }


  /**
   * 模板下载
   */
  exportExclShow() {
    window.location.href = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}sys/classes/down/downMBExcel`;
  }

  /**
   * @author leihfei
   * @date 2019-06-01
   * @description 手动上传文件
   */
  handleUpload(): void {
    if (!this.fileListImport || this.fileListImport.length === 0) {
      this.message.warning('请选择上传文件!');
      return;
    }
    const formData = new FormData();
    this.fileListImport.forEach((file: any) => {
      formData.append('file', file);
    });
    // 执行导入
    this.classManageService.importExcel(formData).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success('导入成功!');
        this.showExcelModal = false;
        this.fileListImport = [];
        // 清除导入文件id
        this.importExcelName = '';
        this.getPage(this.pageInfo);
      }
    });
  }

  /**
   * 文件上传前
   * @ param file
   */
  beforeUpload = (file: UploadFile): boolean => {
    this.fileListImport = [];
    this.fileListImport.push(file);
    this.importExcelName = file.name;
    return false;
  };

  /**
   * @author leihfei
   * @date 2019-06-01
   * @description 删除导入的文件
   */
  delFile() {
    this.fileListImport = [];
    this.importExcelName = '';
  }

}
